#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include "rtsp-server.h"

typedef struct {
	char *name;
	char *addr;
	int port;
	int queuenum;
	int framelen;
	int portmode;
	void (*callback)(int serverId,int status);
}VIM_RTSP_CFG;

extern int VIM_SendStreamToBuf(int serverId, unsigned char *data, int len);

extern int VIM_RtspServerInit(int serverId ,VIM_RTSP_CFG *ServerCofig);

extern void VIM_RtspServerUninit(int serverId);

static inline int startCode3(char *buf)
{
    if (buf[0] == 0 && buf[1] == 0 && buf[2] == 1)
        return 1;
    else
        return 0;
}

static inline int startCode4(char *buf)
{
    if (buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] == 1)
        return 1;
    else
        return 0;
}

static char *findNextStartCode(char *buf, int len)
{
    int i;

    if (len < 3)
        return NULL;

    for (i = 0; i < len - 3; ++i)
    {
        if (startCode3(buf) || startCode4(buf))
            return buf;

        ++buf;
    }

    if (startCode3(buf))
        return buf;

    return NULL;
}

int getFrameFromH265File(int fd, char *frame, int size)
{
    int rSize, frameSize;
    char *nextStartCode;

    if (fd < 0)
        return fd;

    rSize = read(fd, frame, size);

    if (!startCode3(frame) && !startCode4(frame))
        return -1;
restart:
    nextStartCode = findNextStartCode(frame + 3, rSize - 3);
    if (!nextStartCode)
    {
        lseek(fd, 0, SEEK_SET);
        rSize = read(fd, frame, size);
        if (!startCode3(frame) && !startCode4(frame))
            return -1;
        nextStartCode = findNextStartCode(frame + 3, rSize - 3);
        goto restart;
    }
    else
    {
        frameSize = (nextStartCode - frame);
        lseek(fd, frameSize - rSize, SEEK_CUR);
    }

    return frameSize;
}


int main()
{
	VIM_RTSP_CFG serverconf;
	serverconf.addr = "0.0.0.0";
	serverconf.queuenum = 5;
	serverconf.framelen = 1920*1080;
	serverconf.portmode = 0;
	
	
	
	printf("enter main\n");
	int fd = open("./test.265",O_RDWR );
	serverconf.name = "chn0";
	serverconf.port = 8554;
	VIM_RtspServerInit(0,&serverconf);
	serverconf.name = "chn1";
	serverconf.port = 8555;
	VIM_RtspServerInit(1,&serverconf);
	serverconf.name = "chn2";
	serverconf.port = 8556;
	VIM_RtspServerInit(2,&serverconf);
	char *data = (char *)malloc(1920*1080);
	while(1){
		int ret = getFrameFromH265File(fd,data,1920*1080 );
		//printf("ret = %d data1=[%#x] data2=[%#x]data3=[%#x] data4=[%#x]\n",ret, data[0], ret, data[1],ret, data[2],ret, data[3]);
		VIM_SendStreamToBuf(0,data,ret);
		VIM_SendStreamToBuf(1,data,ret);
		VIM_SendStreamToBuf(2,data,ret);
		usleep(40 * 1000);
	}
	free(data);
}



